var CometPresentation = {
	
    _connectionEstablished : function () {
    	Logger.info('CometD Connection Established');
    },

    _connectionBroken : function() {
    	Logger.error('CometD Connection Broken');
    },

    _connectionClosed : function() {
    	Logger.info('CometD Connection Closed');
    },
	
	_metaConnect : function(message) {
		var cometd = $.cometd;
		var settings = CometSettings;

		if (cometd.isDisconnected()) {
        	settings._connected = false;
        	CometPresentation._connectionClosed();
            return;
        }

        var wasConnected = settings._connected;
        settings._connected = message.successful === true;
        if (!wasConnected && settings._connected)
        {
        	CometPresentation._connectionEstablished();
        }
        else if (wasConnected && !settings._connected)
        {
        	CometPresentation._connectionBroken();
        }
    },
	
	_metaHandshake : function(handshake){
		var cometd = $.cometd;
		var settings = CometSettings;
		
        if (handshake.successful === true) {
            cometd.batch(function() {
                cometd.subscribe('/prez/process', function(message) {
                	CometPresentation.updateProgressBar(message.data.progress);
                });
                cometd.publish('/service/prez/process',{
                	command:'start',
                	taskId:settings._taskId
                });
            });
        }
    },
	
	init : function(){
		var cometd = $.cometd;
		var obj = this;

		// Disable the websocket transport
		cometd.websocketEnabled = false;
		
        cometd.addListener('/meta/handshake', obj._metaHandshake);
        cometd.addListener('/meta/connect', obj._metaConnect);

        cometd.handshake();
	},
	
	updateProgressBar : function(value) {
		percent = parseFloat(value);
		$('.bar').width(percent + '%');
		Logger.info('Progress : ' + value + '%');
		if( percent == 100) {
			Logger.info('Conversion Finished !');
			CometPresentation.fireFinishedEvent();
		}
	},
	
	fireFinishedEvent : function (){
		var settings = CometSettings;
		$.ajax({
			url:settings._events.showPrezEvent,
			type:"GET",
			success:function(response) {
				window.location=response.redirectURL;
			},
			error:function(response){
				Logger.error('Ajax request failed');
			}
		});
	}
};